package com.tourism.core.security.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tourism.core.security.entity.LoginUser;
import com.tourism.domain.entity.Menu;
import com.tourism.domain.entity.Role;
import com.tourism.domain.entity.User;
import com.tourism.mapper.MenuMapper;
import com.tourism.mapper.RoleMapper;
import com.tourism.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class LoginService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;


    @Override
    public UserDetails loadUserByUsername(String username) {

        // 根据用户名查询用户
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(username != null, User::getUsername, username));

        // 判断用户是否存在
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        Long userId = user.getId();

        // 获取用户角色
        List<Role> roleList = roleMapper.getRolesByUserId(userId);
        user.setRoles(new HashSet<>(roleList));
        Set<String> roles = roleList.stream().map(Role::getCode).collect(Collectors.toSet());

        // 获取用户权限
        List<Menu> menuList = menuMapper.getMenusByUserId(userId);
        Set<String> permissions = menuList.stream().map(Menu::getPermission).collect(Collectors.toSet());
        user.setPermissions(permissions);

        // 返回用户详情
        return new LoginUser(user, roles, permissions, null);
    }
}